import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor() { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const token: string = sessionStorage.getItem('token') || '';
        const headers = req.headers
            .set('Authorization', token);

        const authReq = req.clone({
            headers: headers
        });
        return next.handle(authReq).do(event => {
            if (event instanceof HttpResponse) {
                // test response to determine action when auth failed
            }
        });
    }
}

export const HttpAuthProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptor,
    multi: true
};
